#ifndef FIRMWARE_UPDATE_H
#define FIRMWARE_UPDATE_H

#include <stdint.h>
#include "param_storage.h"

// Flash布局
#define FLASH_SIZE          (128*1024)  // 128KB
#define FLASH_PAGE_SIZE     0x400       // 1KB per page

// Boot参数在最后1KB
#define BOOT_PARAM_ADDR     (0x8000000 + FLASH_SIZE - FLASH_PAGE_SIZE)  // 0x801FC00

// Bootloader区域(56KB)
#define BOOT_START_ADDR     0x8000000
#define BOOT_SIZE           (56*1024)

// 应用程序区域(60KB)
#define APP_START_ADDR      0x800E000   // 从56KB开始
#define APP_SIZE            (60*1024)   // 60KB大小
#define APP_END_ADDR        (APP_START_ADDR + APP_SIZE)



// 状态定义
#define BOOT_STATE_IDLE    0
#define BOOT_STATE_WRITING 1
#define BOOT_STATE_DONE    2


// 魔数定义
#define BOOT_MAGIC          0xAA55AA55
#define BOOT_FLAG_APP       0x00000000
#define BOOT_FLAG_UPGRADE   0x00000001

typedef enum {
    RUNNING_APP1 = 1,  // 运行在APP1
    RUNNING_APP2 = 2   // 运行在APP2
} RunningApp_t;


typedef struct {
    uint8_t state;         // 当前状态
    uint8_t current_block; // 当前块号(0-59)
    uint32_t crc;         // CRC校验值
} boot_status_t;


typedef struct {
    uint32_t magic;      // 固件魔数 0xAA55AA55
    uint32_t boot_flag;  // 启动标志
    uint32_t fw_size;       // 固件大小
    uint32_t fw_crc;        // 固件CRC
} BootParam_t;


extern boot_status_t boot_status;
// Function declarations
void firmware_update_init(void);
uint8_t firmware_write_block(uint8_t block_num, const uint8_t* data);
uint8_t firmware_verify(uint32_t expected_crc);
uint8_t firmware_activate(void);
uint8_t handle_boot_verify(uint32_t crc);
uint8_t handle_boot_write(uint8_t block_num, uint8_t *data);

uint8_t handle_boot_activate(void);

// Boot参数操作函数声明
HAL_StatusTypeDef write_boot_param(BootParam_t *param);
HAL_StatusTypeDef read_boot_param(BootParam_t *param);
HAL_StatusTypeDef clear_boot_param(void);
#endif // FIRMWARE_UPDATE_H